#include "Rect.h"

//求[a1,b1]和[a2,b2]交集的长度
int overlap(int a1, int b1, int a2, int b2) {
  if (a2 > b1 || a1 > b2) {
    //如果没有交集
    return 0;
  } else if (a1 > a2) {
    if (b1 > b2) {
      return b2 - a1;
    } else {
      return b1 - a1;
    }
  } else {
    if (b2 > b1) {
      return b1 - a2;
    } else {
      return b2 - a2;
    }
  }
}

Rect rectIntersection(const Rect& rect1, const Rect& rect2) {
  int width =
      overlap(rect1.x, rect1.x + rect1.width, rect2.x, rect2.x + rect2.width);
  int height =
      overlap(rect1.y, rect1.y + rect1.height, rect2.y, rect2.y + rect2.height);
  int x = 0;
  int y = 0;
  if (rect1.x >= rect2.x &&
      rect1.y >= rect2.y ) {
    x = rect1.x;
    y = rect1.y;
  } else if (rect2.x >= rect1.x &&
             rect2.y >= rect1.y ) {
    x = rect2.x;
    y = rect2.y;
  } else if (rect1.x + rect1.width >= rect2.x &&
             rect1.x <= rect2.x  &&
             rect1.y >= rect2.y && rect1.y < rect2.y + rect2.height) {
    x = rect2.x;
    y = rect1.y;
  }else if (rect2.x + rect2.width >= rect1.x &&
             rect2.x <= rect1.x &&
             rect2.y >= rect1.y && rect2.y <= rect1.y + rect1.height) {
    x = rect1.x;
    y = rect2.y;
  }
  // } else if (rect1.x + rect1.width >= rect2.x &&
  //            rect1.x + rect1.width < rect2.x + rect2.width &&
  //            rect1.y + rect1.height >= rect2.y &&
  //            rect1.y + rect1.height < rect2.y + rect2.height) {
  //   x = rect2.x;
  //   y = rect1.y;
  // } else if (rect2.x + rect2.width >= rect1.x &&
  //            rect2.x + rect2.width < rect1.x + rect1.width &&
  //            rect2.y + rect2.height >= rect1.y &&
  //            rect2.y + rect2.height < rect1.y + rect1.height) {
  //   x = rect1.x;
  //   y = rect2.y;
  // }

  Rect ret = {x, y, width, height};
  return ret;
}